import React, { Component } from 'react'
import PropTypes from 'prop-types'

import './Add.css'

export default class Add extends Component {
  static propTypes = {
    addComment: PropTypes.func.isRequired
  }
  // 创建 ref 容器
  nameRef = React.createRef();
  contentRef = React.createRef();

  // 提交评论
  submit = () => {
    const name = this.nameRef.current.value;
    const content = this.contentRef.current.value;
    // 判断输入内容是否为空
    if (!name.trim() || !content.trim()) {
      alert('输入内容不能为空');
      return;
    }
    const { addComment } = this.props;
    const comment = {
      id: Date.now(),
      name,
      content
    }
    // 提交评论
    addComment(comment)
    // 清空表单的内容
    this.nameRef.current.value = '';
    this.contentRef.current.value = '';
  }
  render() {
    return (
      <div className="col-md-4">
        <form className="form-horizontal">
          <div className="form-group">
            <label>用户名</label>
            <input type="text" className="form-control" placeholder="用户名" ref={this.nameRef} />
          </div>
          <div className="form-group">
            <label>评论内容</label>
            <textarea className="form-control" rows="6" placeholder="评论内容" ref={this.contentRef}></textarea>
          </div>
          <div className="form-group">
            <div className="col-sm-offset-2 col-sm-10">
              <button type="button" className="btn btn-default pull-right" onClick={this.submit}>提交</button>
            </div>
          </div>
        </form>
      </div>
    )
  }
}